package repository;

import annotation.DependencyInjection;
import annotation.Singleton;
import database.MessageDatabase;
import entity.Message;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Singleton
public class MessageRepository {
    private MessageDatabase database;

    @DependencyInjection
    public MessageRepository(MessageDatabase database) {
        this.database = database;
    }

    public void startWrite() {
        database.startWrite();
    }

    public void endWrite() {
        database.endWrite();
    }

    public void startRead() {
        database.startRead();
    }

    public void endRead() {
        database.endRead();
    }

    public void add(Message message) {
        database.getList().add(message);
    }

    public List<Message> get(String senderUsername, String receiverUsername, LocalDateTime rightEqual) {
        return database.getList().stream().filter(message -> message.getSenderUsername().equals(senderUsername) &&
                message.getReceiverUsername().equals(receiverUsername) && !message.getTime().isAfter(rightEqual)).
            map(Message::new).collect(Collectors.toList());
    }

    public List<Message> get(String senderUsername, String receiverUsername, LocalDateTime left, LocalDateTime rightEqual) {
        return database.getList().stream().filter(message -> message.getSenderUsername().equals(senderUsername) &&
            message.getReceiverUsername().equals(receiverUsername) && message.getTime().isAfter(left) &&
            !message.getTime().isAfter(rightEqual)).map(Message::new).collect(Collectors.toList());
    }
}
